package com.pkk.penguin.frame.know.java.jvm.threadsynch;

import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;

/**
 * @description: 线程安全测试
 * @author: peikunkun
 * @create: 2020-03-03 15:05
 **/
public class ThreadSynchTest {


  @Test
  public void Administrator_12_20200303150605() throws InterruptedException {
    System.out.println("欢迎使用单元测试方法【Administrator_12()_20200303150605】");
    System.out.println("此方法测试描述：【同一个变量被多个线程操作,导致同一个对象被篡改】");

    AtomicReference<StringBuffer> stringBuffer = new AtomicReference<>(new StringBuffer());
    new Thread(() -> {
      stringBuffer.set(method1(stringBuffer.get()));
    }).start();

    Thread.sleep(1000L);
    method2(stringBuffer.get());
    System.out.println(stringBuffer.toString());

    //---------------------同一个变量被多个线程操作,导致同一个对象被篡改-------------------
    AtomicReference<StringBuffer> stringBuffer1 = new AtomicReference<>(new StringBuffer());
    new Thread(() -> {
      stringBuffer1.set(method1(stringBuffer1.get()));
    }).start();

    method2(stringBuffer1.get());
    System.out.println(stringBuffer1.toString());
  }


  public StringBuffer method1(StringBuffer s) {
    s.append("c");
    s.append("d");
    return s;
  }


  public StringBuffer method2(StringBuffer s) {
    s.append("e");
    s.append("f");
    return s;
  }


  public StringBuffer method3() {
    StringBuffer s = new StringBuffer();
    s.append("a");
    return method1(s);
  }


  public StringBuffer method4() {
    StringBuffer s = new StringBuffer();
    s.append("b");
    try {
      Thread.sleep(2000L);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return method1(s);
  }


}
